package com.zpself.module.算法练习.算法;


import org.apache.commons.lang3.ArrayUtils;

import java.util.*;

/**
 *  设计LRU缓存结构，该结构在构造时确定大小，假设大小为K，并有如下两个功能
 * set(key, value)：将记录(key, value)插入该结构
 * get(key)：返回key对应的value值
 * 网址：https://www.nowcoder.com/practice/e3769a5f49894d49b871c09cadd13a61?tpId=188&&tqId=35472&rp=1&ru=/ta/job-code-high-week&qru=/ta/job-code-high-week/question-ranking
**/
public class LRU缓存 {
    public static void main(String[] args) {
        int[][] a={{1,1,1},{1,2,2},{1,3,2},{2,1},{1,4,4},{2,2}};
        int[] lru = new LRU缓存().LRU(a, 3);
        System.out.println(ArrayUtils.toString(lru,","));
        System.out.println(1000==1000);

    }


    /**
     * lru design
     * @param operators int整型二维数组 the ops
     * @param k int整型 the k
     * @return int整型一维数组
     */
    public int[] LRU (int[][] operators, int k) {
        LinkedHashMap<Integer,Integer> lruMap = new LinkedHashMap<Integer, Integer>();
        ArrayList<Integer> result = new ArrayList();

        for (int[] operator : operators) {
            switch(operator[0]){
                case 1:
                    //set
                    if(lruMap.size() < k){
                        lruMap.put(operator[1], operator[2]);
                    }else {
                        Iterator ot = lruMap.keySet().iterator();
                        lruMap.remove(ot.next());
                        lruMap.put(operator[1],operator[2]);
                    }
                    break;
                case 2 :
                    //get
                    if(lruMap.containsKey(operator[1])){
                        int val = lruMap.get(operator[1]);
                        result.add(val);
                        lruMap.remove(operator[1]);
                        lruMap.put(operator[1],val);
                    }else{
                        result.add(-1);
                    }
                    break;
                default:
            }
        }
        int[] resultArr = new int[result.size()];
        int i=0;
        for(int a:result){
            resultArr[i++]=a;
        }
        return  resultArr;
    }
}